package api

import (
	"context"
	"log"
	"os"
	"time"

	"github.com/shirou/gopsutil/cpu"
	"github.com/wailsapp/wails/v2/pkg/runtime"
)

type MonitorApp struct {
	ctx context.Context
}

func NewMonitorApp() *MonitorApp {
	return &MonitorApp{}
}

func (a *MonitorApp) GetSysInfo() {
	go func(ctx context.Context) {
		for {
			percent, err := cpu.Percent(time.Second*2, false)
			if err != nil {
				log.Println(err.Error())
				return
			}
			runtime.EventsEmit(ctx, "sysInfoPublish", float64(int(percent[0]*100))/100)
		}
	}(a.ctx)

}

func (a *MonitorApp) SetContext(ctx context.Context) {
	a.ctx = ctx
	a.GetSysInfo()
	StartWinHooks(a.ctx)
}

func (a *MonitorApp) CloseApp() {
	// 解绑所有事件
	runtime.EventsOffAll(a.ctx)
	// 退出系统
	os.Exit(0)
}
